<?php
// +----------------------------------------------------------------------
// | DTPHP 
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://dtphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: yyj <qingchen.yyj@gmail.com>
// +----------------------------------------------------------------------


namespace app\admin\controller;


use app\admin\model\UpmsRole;
use app\common\base\BaseController;
use app\common\utils\Tools;

class Role extends BaseController
{
    public $table = 'UpmsRole';


    /**
     * @return array|string
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        return $this->_list();
    }


    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function save()
    {
        $this->requestType('POST');
        $role['role_id'] = $this->request->param('id');
        $role['name'] = $this->request->param('name');
        $role['description'] = $this->request->param('description');
        $role['title'] = $this->request->param('title');
        if ($role['role_id'] != 0) {
            $role['role_id'] = (UpmsRole::update($role))->role_id;
        } else {
            $role['role_id'] = (UpmsRole::create($role))->role_id;
        }
        if ($role['role_id']) {
            UpmsRole::get($role['role_id'])->upmsRolePermissions()->detach();
            array_key_exists('permissions', $this->request->param()) ? UpmsRole::get($role['role_id'])->upmsRolePermissions()->attach($this->request->param()['permissions']) : '';
            return $this->buildSuccess([]);
        }

        return $this->buildFailed();
    }

    /**
     * @return array
     * @throws \think\exception\DbException
     */
    public function read()
    {
        $role_id = $this->request->param('id');
        $role = UpmsRole::get(['role_id' => $role_id]);
        if ($role) {
            return $this->buildSuccess($role);
        }
        return $this->buildFailed();
    }

    public function change()
    {

    }

    public function delete()
    {
        $this->requestType('POST');
        $role_id = $this->request->param('id');
        if (UpmsRole::destroy($role_id)) {
            return $this->buildSuccess([]);
        }
        return $this->buildFailed();
    }

}